#!/bin/sh
#
# Script by Graham Keeling.
# Modified for android by Avi Rozen

BASE="$PWD"/..
CROSS="$BASE"/../burp-cross-tools
SRCDIR="$BASE"/src
ORIGPATH=$PATH

VERSION_ZLIB="1.2.8"
VERSION_PCRE="8.38"
VERSION_OPENSSL="1.0.2h"
VERSION_LIBRSYNC="1.0.0"

fail()
{
	echo "Failed"
	exit 1
}

rm_and_mkdir()
{
	rm -rf "$1"
	mkdir -p "$1"
}

do_build()
{
	TGT="$1"
	HOST="$2"
	SSLSUFFIX="$3"
	DEPKGS="$BASE/$TGT"
	if [ -z "$TGT" -o -z "$HOST" ] ; then
		echo "do_build called with not enough parameters"
		fail
	fi
	COMPPREFIX="$CROSS/$TGT/bin/$HOST"-
	BINARY_PATH="$DEPKGS/bin"
	INCLUDE_PATH="$DEPKGS/include"
	LIBRARY_PATH="$DEPKGS/lib"
	MAN_PATH="$DEPKGS/man"
	PATH="$CROSS/$TGT"/bin:$ORIGPATH

	rm -rf "$DEPKGS"
	mkdir -p "$BINARY_PATH"
	mkdir -p "$LIBRARY_PATH"
	mkdir -p "$INCLUDE_PATH"
	mkdir -p "$MAN_PATH"

	echo "build zlib"
	cd $SRCDIR
	rm -rf zlib-"$VERSION_ZLIB"
	tar -zxvf zlib-"$VERSION_ZLIB".tar.gz || fail
	cd zlib-"$VERSION_ZLIB" || fail
	prefix=$DEPKGS CC="$COMPPREFIX"gcc ./configure
	make all || fail
	make install || fail
	cd $SRCDIR
	rm -rf zlib-"$VERSION_ZLIB"

	echo "build pcre"
	cd $SRCDIR
	rm -rf pcre-"$VERSION_PCRE"
	tar -xjvf pcre-"$VERSION_PCRE".tar.bz2 || fail
	cd pcre-"$VERSION_PCRE" || fail
	./configure CC_FOR_BUILD=gcc \
		CXX_FOR_BUILD=g++ \
		--host=$HOST \
		--prefix=$DEPKGS \
		--enable-utf8 \
		--enable-unicode-properties || fail
	make PREFIX=$DEPKGS all || fail
	make PREFIX=$DEPKGS install || fail
	cd $SRCDIR
	rm -rf pcre-"$VERSION_PCRE"

	echo "build openssl"
	cd $SRCDIR
	rm -rf openssl-"$VERSION_OPENSSL"
	tar -zxvf openssl-"$VERSION_OPENSSL".tar.gz || fail
	cd openssl-"$VERSION_OPENSSL" || fail
	./Configure no-shared zlib no-dso threads \
	    --prefix=$DEPKGS \
	    --with-zlib-include=$INCLUDE_PATH \
	    --cross-compile-prefix=$COMPPREFIX linux-generic32|| fail
	make all || fail
	make install_sw || fail
	cd $SRCDIR
	rm -rf openssl-"$VERSION_OPENSSL"

	echo "build librsync"
	cd $SRCDIR
	rm -rf librsync-"$VERSION_LIBRSYNC"
	tar -zxvf librsync-"$VERSION_LIBRSYNC".tar.gz || fail
	cd librsync-"$VERSION_LIBRSYNC" || fail
	patch -Np1 <$SRCDIR/librsync-patches/001-no-rdiff.patch || fail
	rm config.sub
	./autogen.sh || fail
	./configure --host=$HOST --prefix=$DEPKGS || fail
	make || fail
	make install || fail
	cd $SRCDIR
	rm -rf librsync-"$VERSION_LIBRSYNC"

	echo "Finished OK"

}

do_build android arm-linux-androideabi android
